package com.achievo.know.pojo;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

import com.achievo.know.domain.FileAttachment;
import com.achievo.know.domain.TempAttachment;

public class FileHandle {

	public static boolean move(File oDire,File dDire,FileAttachment a){
		boolean result=false;
		java.io.File ofile=null;
		try {
			ofile=new java.io.File(oDire+"/"+a.getAttachPath()+a.generateFileName());
			java.io.File path=new java.io.File(dDire+"/"+a.getAttachPath());
			if(!path.exists()){
				FileUtils.forceMkdir(path);
			}
			if(ofile.exists())
				FileUtils.copyFileToDirectory(ofile,path, true);
			result=true;
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally{
			if(result&&ofile!=null){
				try {
					if(ofile.exists())
						FileUtils.forceDelete(ofile);
				} catch (IOException e) {
					e.printStackTrace();
					result=false;
				}
			}
		}
		return result;
	}
	
	public static boolean copy(File oDire,File dDire,FileAttachment a){
		boolean result=false;
		java.io.File ofile=null;
		try {
			ofile=new java.io.File(oDire+"/"+a.getAttachPath()+a.generateFileName());
			java.io.File path=new java.io.File(dDire+"/"+a.getAttachPath());
			if(!path.exists()){
				FileUtils.forceMkdir(path);
			}
			if(ofile.exists())
				FileUtils.copyFileToDirectory(ofile,path, true);
			result=true;
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return result;
	}
	
	public static boolean move(File oDire,File dDire,TempAttachment a){
		boolean result=false;
		java.io.File ofile=null;
		try {
			ofile=new java.io.File(oDire+"/"+a.getAttachPath()+a.getGuid()+"."+a.getAttachType());
			java.io.File path=new java.io.File(dDire+"/"+a.getAttachPath());
			if(!path.exists()){
				FileUtils.forceMkdir(path);
			}
			if(ofile.exists())
				FileUtils.copyFileToDirectory(ofile,path, true);
			result=true;
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally{
			if(result&&ofile!=null){
				try {
					FileUtils.forceDelete(ofile);
				} catch (IOException e) {
					e.printStackTrace();
					result=false;
				}
			}
		}
		return result;
	}
}
